package com.jinglin.admin.Interceptor;

import com.jinglin.component.RedisComponent;
import com.jinglin.entity.constants.Constants;
import com.jinglin.entity.dto.TokenUserInfoDto;
import com.jinglin.entity.enums.ResponseCodeEnum;
import com.jinglin.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AppInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisComponent redisComponent;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // handler是SpringMVC请求处理的具体对象。(其实就是接受请求的方法)
        // 通常是HandlerMethod类型
        if (handler == null){
            return false;
        }
        if ( !(handler instanceof HandlerMethod)){
            return  true;
        }
        // 登录不拦截
        if (request.getRequestURI().contains("/account")){
            return true;
        }
        String token = request.getHeader(Constants.TOKEN_ADMIN);
        // 文件不拦截
        if (request.getRequestURI().contains("/file")){
            token = getTokenFromCookie(request);
        }
        // 如果没有token，则抛出异常，拦截去登录。
        if (token == null || token.isEmpty()){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }

        String  account = redisComponent.getAdminTokenAccount(token);
        if (account == null){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }


        return true;
    }

    private String getTokenFromCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies){
                if (cookie.getName().equals(Constants.TOKEN_ADMIN)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
